﻿using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YouDaoNotesCodes.OperateJavaScript
{
    class ExecuteJS
    {
        #region 利用Microsoft.JScript.Vsa
        static VsaEngine Engine = VsaEngine.CreateEngine();//缺点：Vsa的功能比较有限，多条语句执行时，只返回最后一条语句的执行结果。
        public void ExeJS()
        {
            try
            {
                var i = (int)EvalJScript("1+2;");
                Console.WriteLine(i);//3
                var d = (DateObject)EvalJScript("var d = new Date(2013,9-1,2,20,30,15)");
                Console.WriteLine(d);//Mon Sep 2 20:30:15 UTC+8 2013
                var j = EvalJScript("function add(x,y){return x+y;};add(5,10);");
                Console.WriteLine(j);//15
                var obj = EvalJScript("var obj = {};obj.name='jimmy';obj.sex='Male';");
                Console.WriteLine(obj);//Male 注：只返回最后一条执行的语句结果
                Console.Read();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
        static object EvalJScript(string JScript)
        {
            object Result = null;
            try
            {
                Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return Result;

        }
        #endregion

        #region COM组件：Microsoft Script Control 1.0（13和17都没有）
        //参考1：https://www.cnblogs.com/jcdd-4041/p/4245588.html
        //参考2：https://www.cnblogs.com/coolsundy/p/7116123.html
        #endregion
    }
}
